package com.ruoyi.campus.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.campus.mapper.DepartmentMapper;
import com.ruoyi.campus.domain.Department;
import com.ruoyi.campus.service.IDepartmentService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.constant.UserConstants;

/**
 * 部门信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-08
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService 
{
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询部门信息
     * 
     * @param deptId 部门信息主键
     * @return 部门信息
     */
    @Override
    public Department selectDepartmentByDeptId(Long deptId)
    {
        return departmentMapper.selectDepartmentByDeptId(deptId);
    }

    /**
     * 查询部门信息列表
     * 
     * @param department 部门信息
     * @return 部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Department> selectDepartmentList(Department department)
    {
        return departmentMapper.selectDepartmentList(department);
    }

    /**
     * 新增部门信息
     * 
     * @param department 部门信息
     * @return 结果
     */
    @Override
    public int insertDepartment(Department department, String operName)
    {
        // 如果父节点ID为空或为0，说明是根节点
        if (department.getParentId() == null || department.getParentId() == 0)
        {
            department.setAncestors("0");
        }
        else
        {
            Department info = departmentMapper.selectDeptById(department.getParentId());
            // 如果父节点不存在
            if (info == null)
            {
                throw new ServiceException("父节点不存在");
            }
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!Department.NORMAL.equals(info.getStatus()))
            {
                throw new ServiceException("部门停用，不允许新增");
            }
            department.setAncestors(info.getAncestors() + "," + department.getParentId());
        }
        department.setCreateTime(DateUtils.getNowDate());
        department.setCreateBy(operName);
        return departmentMapper.insertDepartment(department);
    }

    /**
     * 修改部门信息
     * 
     * @param department 部门信息
     * @return 结果
     */
    @Override
    public int updateDepartment(Department department, String operName)
    {
        Department newParentDept = departmentMapper.selectDeptById(department.getParentId());
        Department oldDept = departmentMapper.selectDeptById(department.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            department.setAncestors(newAncestors);
            updateDeptChildren(department.getDeptId(), newAncestors, oldAncestors);
        }
        department.setUpdateTime(DateUtils.getNowDate());
        department.setUpdateBy(operName);
        int result = departmentMapper.updateDepartment(department);
        if (Department.NORMAL.equals(department.getStatus()) && StringUtils.isNotEmpty(department.getAncestors())
                && !StringUtils.equals("0", department.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(department);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param department 当前部门
     */
    private void updateParentDeptStatusNormal(Department department)
    {
        String ancestors = department.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        departmentMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<Department> children = departmentMapper.selectChildrenDeptById(deptId);
        for (Department child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            departmentMapper.updateDeptChildren(children);
        }
    }

    /**
     * 批量删除部门信息
     * 
     * @param deptIds 需要删除的部门信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDeptIds(Long[] deptIds)
    {
        for (Long deptId : deptIds)
        {
    
            Department department = selectDeptById(deptId);
            if (hasChildByDeptId(deptId))
            {
                throw new ServiceException(String.format("%1$s存在子部门,不允许删除", department.getDeptName()));
            }
            if (checkDeptExistUser(deptId))
            {
                throw new ServiceException(String.format("%1$s部门存在用户,不允许删除", department.getDeptName()));
            }
            if (departmentMapper.checkDeptExistPoint(deptId) > 0)
            {
                throw new ServiceException(String.format("%1$s部门存在点位,不允许删除", department.getDeptName()));
            }
            if (departmentMapper.checkDeptExistGuard(deptId) > 0)
            {
                throw new ServiceException(String.format("%1$s部门存在安全员,不允许删除", department.getDeptName()));
            }
        }
        return departmentMapper.deleteDepartmentByDeptIds(deptIds);
    }

    /**
     * 删除部门信息信息
     * 
     * @param deptId 部门信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDeptId(Long deptId)
    {
        return departmentMapper.deleteDepartmentByDeptId(deptId);
    }

    /**
     * 查询部门管理树列表
     * 
     * @param department 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDepartmentTree(Department department)
    {
        List<Department> deptList = departmentMapper.selectDepartmentList(department);
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Department dept : deptList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(dept.getDeptId());
            ztree.setpId(dept.getParentId());
            ztree.setName(dept.getDeptName());
            ztree.setTitle(dept.getDeptName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param departments 部门列表
     * @return 树结构列表
     */
    @Override
    public List<Department> buildDeptTree(List<Department> departments)
    {
        List<Department> returnList = new ArrayList<Department>();
        List<Long> tempList = new ArrayList<Long>();
        for (Department dept : departments)
        {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<Department> iterator = departments.iterator(); iterator.hasNext();)
        {
            Department dept = (Department) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(departments, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = departments;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param departments 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Ztree> buildDeptTreeSelect(List<Department> departments)
    {
        List<Department> deptTrees = buildDeptTree(departments);
        return initZtree(deptTrees, null, false);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptCheckedKeys 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Department> deptList, List<String> roleDeptCheckedKeys, boolean permsFlag)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptCheckedKeys);
        for (Department dept : deptList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(dept.getDeptId());
            ztree.setpId(dept.getParentId());
            ztree.setName(dept.getDeptName());
            ztree.setTitle(dept.getDeptName());
            if (isCheck)
            {
                ztree.setChecked(roleDeptCheckedKeys.contains(dept.getDeptId() + dept.getDeptName()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<Department> list, Department t)
    {
        // 得到子节点列表
        List<Department> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Department tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Department> getChildList(List<Department> list, Department t)
    {
        List<Department> tlist = new ArrayList<Department>();
        Iterator<Department> it = list.iterator();
        while (it.hasNext())
        {
            Department n = (Department) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Department> list, Department t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public Department selectDeptById(Long deptId)
    {
        return departmentMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return departmentMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在部门子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = departmentMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = departmentMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(Department dept)
    {
        Department info = departmentMapper.checkDeptNameUnique(dept.getDeptName(), dept.getDeptId());
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门编码是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptCodeUnique(Department dept)
    {
        Department info = departmentMapper.checkDeptCodeUnique(dept.getDeptCode(), dept.getDeptId());
        if (StringUtils.isNotNull(info))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 批量删除部门信息
     *
     * @param ids 需要删除的部门信息主键集合字符串
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDeptIds(String ids)
    {
        Long[] deptIds = Convert.toLongArray(ids);
        return deleteDepartmentByDeptIds(deptIds);
    }

    /**
     * 获取部门点位数量统计
     *
     * @param deptId 部门ID
     * @return 点位数量
     */
    @Override
    public int getPointCountByDeptId(Long deptId)
    {
        return departmentMapper.getPointCountByDeptId(deptId);
    }
}